import { TreeGraph } from "@antv/g6";
import parser from "./parser";

const defaultG6Options = {
  container: null,
  layout: {
    // dendrogram
    // compactBox
    // mindmap
    // indeted
    type: "mindmap",
    direction: "H",
    nodeSep: 40,
  },
  modes: {
    default: [
      {
        type: "collapse-expand",
        onChange: function onChange(item, collapsed) {
          const data = item.get("model");
          data.collapsed = collapsed;
          return true;
        },
      },
      "drag-canvas",
      "zoom-canvas",
    ],
  },
  defaultEdge: {
    type: "arc",
    style: {
      stroke: "#007acc",
      lineWidth: 1,
    },
    autoRotate: true,
  },
  defaultNode: {
    type: "rect",
    autoEllipsis: true,
    style: {
      radius: 4,
      stroke: '#007acc'
    },
    anchorPoints: [
      [0.5, 0.5]
    ],
    labelCfg: {
      style: {
        fill: '#000',
        fontSize: 14
      }
    }
  },
}

/**
 * 
 * @param {Element} container 
 */
function createToolbar(container, sheets, buttons, toolbarPrefix, toolbarSuffix) {
  const id = 'xmind-viewer--toolbar'
  let toolbar = document.getElementById(id)
  if (!toolbar) {
    toolbar = document.createElement('div')
    toolbar.id = id
    container.appendChild(toolbar)
  }

  toolbar.innerHTML = ''

  const sheetsEl = document.createElement('div')
  sheetsEl.className = id + '-sheets'
  toolbar.appendChild(sheetsEl)

  sheets.forEach(sheet => {
    const sheetEl = document.createElement('div')
    sheetsEl.appendChild(sheetEl)

    const button = document.createElement('button')
    button.textContent = sheet.text
    button.onclick = sheet.handler
    sheetEl.appendChild(button)
  })

  const buttonsEl = document.createElement('div')
  buttonsEl.className = id + '-buttons'
  toolbar.appendChild(buttonsEl)

  // 默认的按钮
  buttons.forEach(button => {
    const el = document.createElement('button')
    el.textContent = button.text
    el.onclick = button.handler
    buttonsEl.appendChild(el)
  })

  if (toolbarPrefix?.length) {
    const prefix = document.createElement('div')
    prefix.className = id + '-prefix'
    toolbar.insertBefore(prefix, sheetsEl)

    toolbarPrefix.forEach(item => {
      prefix.appendChild(item)
    })
  }

  if (toolbarSuffix?.length) {
    const suffix = document.createElement('div')
    suffix.className = id + '-suffix'
    toolbar.appendChild(suffix)

    toolbarSuffix.forEach(item => {
      suffix.appendChild(item)
    })
  }
}

function renderSheet(graph, sheet) {
  const data = parser.resolve(sheet);
  graph.data(data);
  graph.render();
  graph.fitView();
}

/**
 * 
 * @param {Element} container 指定渲染容器
 * @param {ArrayBuffer} fileData 文件内容
 * @param {Object} [g6Options] G6 TreeGraph 的选项
 * @param {Array<Element} [toolbarPrefix] 要附加到工具条开始处的元素
 * @param {Array<Element} [toolbarSuffix] 要附加到工具条结尾处的元素
 * @returns {Promise<TreeGraph>} G6.TreeGraph 实例
 */
async function render(container, fileData, g6Options, toolbarPrefix, toolbarSuffix) {
  g6Options = Object.assign({}, defaultG6Options, g6Options)
  if (!g6Options.container) {
    g6Options.container = container
  }

  let graph = container.__graph
  if (!graph) {
    graph = container.__graph = new TreeGraph(g6Options);

    window.onresize = () => {
      if (!graph || graph.get("destroyed")) return;
      if (!container || !container.scrollWidth || !container.scrollHeight) return;
      graph.changeSize(container.scrollWidth, container.scrollHeight);
    };
  } else {
    graph.clear()
  }

  const sheets = await parser.load(fileData);
  if (!sheets.length) {
    return graph
  }
  renderSheet(graph, sheets[0])
  createToolbar(container, sheets.map((sheet, i) => {
    return {
      text: sheet.title || `未命名-${i + 1}`,
      handler: () => {
        graph.clear()
        renderSheet(graph, sheet)
      }
    }
  }), [{
    text: '居中',
    handler: () => {
      graph.fitCenter()
    }
  }, {
    text: '适应',
    handler: () => {
      graph.fitView();
    }
  }], toolbarPrefix, toolbarSuffix)

  return graph
}

export default {
  render,
  defaultG6Options
}